
import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart' as MyGet;
import 'package:laos_mall/app_route.dart';
import 'package:laos_mall/common/widght/toast/showtoast.dart';
import 'package:logger/logger.dart';
import '../utils/http_util.dart';
import '../utils/storage_util.dart';

class MyInterceptor extends Interceptor {
  @override
  Future<void> onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    //需要过滤掉token
    // if (options.path == '/projecta/verificationcode' ||
    //     options.path == '/harbor/userLogin/accountRegister' ||
    //     options.path == '/harbor/userLogin/userForgetPassword') {
    // } else {
    // }
    if (StorageUtils().getToken() != null) {
      options.headers['Authorization'] = "Bearer  ${StorageUtils().getToken()}";
    }

    debugPrint("requestUrl---->:${options.uri}");
    debugPrint("requestParam--headers--->:${options.headers}");
    debugPrint("requestParam--->:${options.queryParameters}");
    return handler.next(options);
  }

  @override
  Future<void> onResponse(Response response, ResponseInterceptorHandler handler) async {
    debugPrint('response-data--->:${response.data}  response-url = ${response.realUri}');
    try {
      var code = response.data["code"] as int?;
      //token无效需要重新登陆
      if (response.data["code"] == 401) {
        // StorageUtils().clearAll();
        // MyGet.Get.offAll(()=>LoginPage());
        //MyGet.Get.offAndToNamed(LoginView.routeName);
      }

      if (response.data["code"] != 0) {

        if (!HttpUtil.showErrorDialog) {
          String msg = "";
          // switch (code){
          //   case 500:
          //     msg = "服务器错误";
          //     break;
          // }
         if(code == null){
           msg = "服务器错误";
         }else{
           msg = response.data["msg"].toString();
         }
          SmartDialog.showToast(msg);
        }
      }else{
        ///接口成功
        if( response.data["data"]["errcode"] != 0){
          if(response.data["data"]["errcode"] == 401){
            MyGet.Get.toNamed(AppRouter.login);
            return;
          }
          if(response.data["data"]["message"] != null){
            showToast(response.data["data"]["message"]);
          }
          if(response.data["data"]["msg"] != null){
            String message = response.data["data"]["msg"];
            if(message.isNotEmpty && message != "ok"){
              showToast(message);
            }

          }
        }
      }
    }catch(e,stackTrace){
      Logger().e(e);
      Logger().e(stackTrace);
    }
    return handler.next(response);
  }


  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    debugPrint(err.message);
    super.onError(err, handler);
  }
}
